package cn.com.czpb.client.custorm;


import android.app.Activity;
import android.content.Context;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewStub;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextView;

import cn.com.czpb.client.R;
import cn.com.czpb.client.module.version.AlertAnimateUtil;
import cn.com.czpb.client.module.version.OnDismissListener;
import cn.com.czpb.client.module.version.OnItemClickListener;
import cn.com.czpb.client.utils.LogUtils;

import java.util.ArrayList;


/**
 * Created by 猪猪侠 on 2017/7/14.
 */

public class AlertView {
    private ViewGroup decorView;//activity的根View
    private ViewGroup rootView;//AlertView 的 根View
    private ViewGroup contentContainer;
    private int gravity = Gravity.CENTER;
    private Animation outAnim;
    private Animation inAnim;
    private ArrayList<String> mDatas = new ArrayList<String>();
    private OnDismissListener onDismissListener;
    private OnItemClickListener mOnItemClickListener;
    public static final int CANCELPOSITION = -1;//点击取消按钮返回 －1，其他按钮从0开始算
    private String mTitle;//标题
    private String mMsg;//内容
    private String mCancel;//推出按钮
    private String mDestructive;//确定按钮
    private Context mContext;//context
    private boolean isShowing;//展示flag
    private ViewGroup loAlertHeader;//窗口headerView
    private final FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(
            ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, Gravity.BOTTOM
    );
    public AlertView(String title, String msg, String cancel,String destructive,Context context, OnItemClickListener onItemClickListener){
        mOnItemClickListener = onItemClickListener;
        this.mTitle = title;//标题
        this.mMsg = msg;
        this.mCancel = cancel;
        this.mDestructive = destructive;
        this.mContext = context;
        if (destructive!=null){
            this.mDatas.add(destructive);
        }
        this.mDatas.add(0, cancel);
        initView();
        init();
    }
    private void initView(){
        if (mContext == null) return;
        LayoutInflater layoutInflater = LayoutInflater.from(mContext);
        decorView = ((Activity) mContext).getWindow().getDecorView().findViewById(android.R.id.content);
        rootView = (ViewGroup) layoutInflater.inflate(R.layout.layout_alertview, decorView, false);
        rootView.setLayoutParams(new FrameLayout.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT
        ));
        contentContainer = rootView.findViewById(R.id.content_container);
        int margin_alert_left_right = 0;
        params.gravity = Gravity.CENTER;
        margin_alert_left_right = mContext.getResources().getDimensionPixelSize(R.dimen.margin_alert_left_right);
        params.setMargins(margin_alert_left_right, 0, margin_alert_left_right, 0);
        contentContainer.setLayoutParams(params);
        gravity = Gravity.CENTER;
        initAlertViews(layoutInflater);
    }

    protected void initAlertViews(LayoutInflater layoutInflater) {
        if (mContext == null) return;
        ViewGroup viewGroup = (ViewGroup) layoutInflater.inflate(R.layout.layout_alertview_alert, contentContainer);
        initHeaderView(viewGroup);
        int position = 0;
        //如果总数据小于等于HORIZONTAL_BUTTONS_MAXCOUNT，则是横向button
            ViewStub viewStub = contentContainer.findViewById(R.id.viewStubHorizontal);
            viewStub.inflate();
            LinearLayout loAlertButtons = contentContainer.findViewById(R.id.loAlertButtons);
            for (int i = 0; i < mDatas.size(); i++) {
                //如果不是第一个按钮
                if (i != 0) {
                    //添加上按钮之间的分割线
                    View divier = new View(mContext);
                    divier.setBackgroundColor(mContext.getResources().getColor(R.color.color_e8e8e8));
                    LinearLayout.LayoutParams params = new LinearLayout.LayoutParams((int) mContext.getResources().getDimension(R.dimen.size_divier), LinearLayout.LayoutParams.MATCH_PARENT);
                    loAlertButtons.addView(divier, params);
                }
                View itemView = LayoutInflater.from(mContext).inflate(R.layout.item_alertbutton, null);
                TextView tvAlert = itemView.findViewById(R.id.tvAlert);
                tvAlert.setClickable(true);

                //设置点击效果
                if (mDatas.size() == 1) {
                    tvAlert.setBackgroundResource(R.drawable.bg_alertbutton_bottom);
                } else if (i == 0) {//设置最左边的按钮效果
                    tvAlert.setBackgroundResource(R.drawable.bg_alertbutton_left);
                } else if (i == mDatas.size() - 1) {//设置最右边的按钮效果
                    tvAlert.setBackgroundResource(R.drawable.bg_alertbutton_right);
                }
                String data = mDatas.get(i);
                tvAlert.setText(data);

                //取消按钮的样式
                if (data == mCancel) {
                    tvAlert.setTextColor(mContext.getResources().getColor(R.color.color_1a1a1a));
                    tvAlert.setOnClickListener(new OnTextClickListener(CANCELPOSITION));
                    position = position - 1;
                }
                //高亮按钮的样式
                else if (mDestructive != null && mDestructive.contains(data)) {
                    tvAlert.setTextColor(mContext.getResources().getColor(R.color.colorPrimary));
                }

                tvAlert.setOnClickListener(new OnTextClickListener(position));
                position++;
                loAlertButtons.addView(itemView, new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
                        LinearLayout.LayoutParams.WRAP_CONTENT, 1));
            }


    }
    //添加进度条view
    public AlertView addExtView(View extView) {
        loAlertHeader.addView(extView);
        return this;
    }

    private void initHeaderView(ViewGroup viewGroup){
        loAlertHeader = viewGroup.findViewById(R.id.loAlertHeader);
        //标题和消息
        TextView tvAlertTitle = viewGroup.findViewById(R.id.tvAlertTitle);
        TextView tvAlertMsg = viewGroup.findViewById(R.id.tvAlertMsg);
        if (mTitle != null) {
            tvAlertTitle.setText(mTitle);
        } else {
            tvAlertTitle.setVisibility(View.GONE);
        }
        if (mMsg != null) {
            tvAlertMsg.setText(mMsg);
        } else {
            tvAlertMsg.setVisibility(View.GONE);
        }
    }


    public AlertView setOnDismissListener(OnDismissListener onDismissListener) {
        this.onDismissListener = onDismissListener;
        return this;
    }

        protected void init() {
            inAnim = getInAnimation();
            outAnim = getOutAnimation();
        }

    public Animation getInAnimation() {
        if (mContext == null) return null;

        int res = AlertAnimateUtil.getAnimationResource(this.gravity, true);
        return AnimationUtils.loadAnimation(mContext, res);
    }

    public Animation getOutAnimation() {
        if (mContext == null) return null;

        int res = AlertAnimateUtil.getAnimationResource(this.gravity, false);
        return AnimationUtils.loadAnimation(mContext, res);
    }
    class OnTextClickListener implements View.OnClickListener {

        private int position;

        public OnTextClickListener(int position) {
            this.position = position;
        }

        @Override
        public void onClick(View view) {
            if (mOnItemClickListener != null)
                mOnItemClickListener.onItemClick(AlertView.this, position);
            dismiss();
        }
    }
    public void dismiss() {
        //消失动画
        outAnim.setAnimationListener(outAnimListener);
        contentContainer.startAnimation(outAnim);
    }
    private Animation.AnimationListener outAnimListener = new Animation.AnimationListener() {
        @Override
        public void onAnimationStart(Animation animation) {

        }

        @Override
        public void onAnimationEnd(Animation animation) {
            dismissImmediately();
        }

        @Override
        public void onAnimationRepeat(Animation animation) {

        }
    };
    public void dismissImmediately() {
        decorView.removeView(rootView);
        isShowing = false;
        if (onDismissListener != null) {
            onDismissListener.onDismiss(this);
        }

    }
    public AlertView setCancelable(boolean isCancelable) {
        View view = rootView.findViewById(R.id.outmost_container);

        if (isCancelable) {
            view.setOnTouchListener(onCancelableTouchListener);
        } else {
            view.setOnTouchListener(null);
        }
        return this;
    }
    /**
     * Called when the user touch on black overlay in order to dismiss the dialog
     */
    private final View.OnTouchListener onCancelableTouchListener = new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            if (event.getAction() == MotionEvent.ACTION_DOWN) {
                dismiss();
            }
            return false;
        }
    };
    /**
     * show的时候调用
     *
     * @param view 这个View
     */
    private void onAttached(View view) {
        LogUtils.i("show-->3");
        isShowing = true;
        decorView.addView(view);
        contentContainer.startAnimation(inAnim);
    }
    /**
     * 添加这个View到Activity的根视图
     */
    public void show() {
        LogUtils.i("isshowing-->"+isShowing);
        if (isShowing()) {
            return;
        }
        onAttached(rootView);
    }
    /**
     * 检测该View是不是已经添加到根视图
     *
     * @return 如果视图已经存在该View返回true
     */
    public boolean isShowing() {
        return rootView.getParent() != null && isShowing;
    }

}
